App({
  onLaunch () {
    wx.getSystemInfo({
      success: e => {
        this.globalData.getSystemInfoSync = e
        this.globalData.gd = e.screenHeight
        this.globalData.StatusBar = e.statusBarHeight
        let capsule = wx.getMenuButtonBoundingClientRect()
        if (capsule) {
          this.globalData.Custom = capsule
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50
        }
      }
    })
    let userInfo = wx.getStorageSync("userInfo")
    if (userInfo) {
      this.globalData.userInfo = wx.getStorageSync("userInfo").userInfo
      //console.log('app.js 缓存读取的信息：',wx.getStorageSync("userInfo").userInfo )
    }else {
      let reuserInfo = {
        errMsg: 'getUserProfile:没登陆匿名数据',
        userInfo: {
          avatarUrl: "http://p1.music.126.net/A1icMHK6BRPwC3NF5WqxIw==/3400789472720816.jpg",//nulltx
          city: '东瀛',
          country: '神州',
          gender: '♂',
          language: '简体中文',
          nickName: '未登录',
          province: '华夏'
        }
      }
      wx.setStorageSync('userInfo', reuserInfo)
      //console.log('app.js 没登陆的匿名数据',reuserInfo)
    }
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      //console.log('app.js 云开始初始化环境👇填写你的云开发ID')
      wx.cloud.init({
        //env: 'your-id' 删除//
      })
    }
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function(res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function() {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经上线啦~，为了获得更好的体验，建议立即更新',
              showCancel: false,
              confirmColor: "#5677FC",
              success: function(res) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            })
          })
          updateManager.onUpdateFailed(function() {
            // 新的版本下载失败
            wx.showModal({
              title: '更新失败',
              content: '新版本更新失败，为了获得更好的体验，请您删除当前小程序，重新搜索打开',
              confirmColor: "#5677FC",
              showCancel: false
            })
          })
        }
      })
    } else {
      // 当前微信版本过低，无法使用该功能
    }
  },
  globalData: {
    userInfo:[],
    getSystemInfoSync:[],
    isLogin: wx.getStorageSync("userInfo").errMsg=='getUserProfile:没登陆匿名数据' ? false : true
  }
})

export function at_pages() {
  return Component({
    properties: {
      onload: {
        type: Number,
        value: 1
      },
      mdtap: String,
      bts: Boolean,
      isOpenAdMode: Number,
      AdModename: String,
      AdModename2: String,
      s9h1: String,
      s9h2: String,
      s0h1: String,
      s0h2: String,
      wavepanda: {
        type:String,
        value:"https://cms.cnc.blzstatic.cn/cms/blog_header/c3/C3T5INSE3JXK1632995969938.jpg"
      },
      hasui: Boolean,
      name: String,
      tm: String,
      disable: Number,
      qsybtn: String,
      qsyinput: String,
      openid: String,
      showss: String,
      version: String,
      noticetz: String,
      vertion_bind: String,
      pdbt: Number,
      banner: {
        type: String,
        value: 'http://p1.music.126.net/mvlWSJp9Y3c8kuVr2Uma5g==/109951162779809851.jpg',
      },
      bing: String,
      sc: String,
      si: String,
      gg: Boolean,
      based: Boolean,
      color: {
        type: String,
        value: 'blue'
      },
      hh: {
        type: String,
        value: ''
      },
      url: {
        type: String,
        value: ''
      },
      title: {
        type: String,
        value: "抖音去水印 · 无广告无限制"
      },
      h1: String,
      h2: String,
      hp: Number,
      hpp: Number,
      i: {
        type: Number,
        value: 1
      },
      ih: {
        type: Number,
        value: 422
      },
      btncolor: String,
      shuru: String,
    },
    data: {
      wave:"https://tinypng.com/images/apng/panda-waving-2x.png",
      modal3: false,
      button3: [{
        text: "确定",
        type: 'vip'
      }],
      gd: getApp().globalData.gd,
      show: false,
      skeletonShow: true,
      ads: [{
        uid: '79af4f00c0e2e2b6'
      }
      ],
      CustomBar: getApp().globalData.CustomBar,
      numberArr: ['2', '2', '3', '3'],
      pwdArr: ["", "", "", "", "", ""],
      temp: ["", "", "", "", "", ""],
      xt: getApp().globalData.getSystemInfoSync,
      wavepandas:"https://tinypng.com/images/apng/panda-waving.png",
      policy: "http://p1.music.126.net/yAzYPJuOWQJfxvEvmPOIDw==/109951164438195277.jpg"
    },
    methods: {
      输入(e) {
        this.setData({
          shuru: e.detail.value,
          bts: true,
        });
        //console.log(e.detail.value)
        this.triggerEvent('sr', e.detail.value);
      },
      清空(e) {
        this.setData({
          shuru: ""
        });
        this.triggerEvent('clear');
      },
      广告模式() {
        wx.reLaunch({
          url: '/packages/packageA/adindex/index',
        });
      },
      外卖红包(){
        wx.navigateToMiniProgram({
          appId: 'wxece3a9a4c82f58c9',
          //envVersion: envVersion,
          //extraData: extraData,
          path: 'taoke/pages/shopping-guide/index?scene=yVQhyiu',
          success: (res) => {
            console.log(res,'success')
          },
          fail: (res) => {
            console.log(res,'fail')
          },
          complete: (res) => {
            console.log(res,'complete')
          }
        })
      },
      饿了么(){
        wx.navigateToMiniProgram({
          appId: 'wxece3a9a4c82f58c9',
          //envVersion: envVersion,
          //extraData: extraData,
          path: 'taoke/pages/shopping-guide/index?scene=yVQhyiu',
          success: (res) => {
            console.log(res,'success')
          },
          fail: (res) => {
            console.log(res,'fail')
          },
          complete: (res) => {
            console.log(res,'complete')
          },
        })
      },
      按钮复位() {
        this.triggerEvent("remove");
      },
      按钮位移() {
        this.triggerEvent("move");
      },
      回到首页() {
        wx.switchTab({
          url: '/pages/index',
        });
      },
      用户信息() {
        this.triggerEvent('login');
      },
      没登陆() {
        this.triggerEvent('mdl');
      },
      去水印() {
        this.triggerEvent('qsy');
      },
      广告() {
        this.triggerEvent('gg');
      },
      缓冲中() {
        console.log('视频缓冲中');
      },
      加载完成() {
        console.log('加载完成');
      },
      登录() {
        this.setData({
          modal3: !this.data.modal3
        });
      },
      handleClick3() {
        this.triggerEvent('login');
        this.setData({
          modal3: false
        });
      },
      全屏显示(e) {
        let link = e.currentTarget.dataset.u;
        wx.navigateTo({
          url: '/packages/packageA/history/preview/index?douyinlink=' + link,
        });
      },
      隐藏页面() {
        this.navigate('/packages/packageA/view/index');
      },
      保存图片(w) {
        let img = w.currentTarget.dataset.p;
        wx.previewImage({
          current: img,
          urls: [img] // 需要预览的图片http链接列表
        });
      },
      自定义壁纸() {
        this.triggerEvent('base');
      },
      换视频() {
        this.triggerEvent('bc3');
      },
      换视频5() {
        this.triggerEvent('bc5');
      },
      无聊() {
        this.triggerEvent('sb');
      },
      switchKeyboard(e) {
        let length = 4;
        let arr = ["", "", "", "", "", ""];
        if (length == 4) {
          arr = ["", "", "", ""];
        }
        this.setData({
          pwdArr: arr,
          temp: arr,
          numberArr: []
        }, () => {
          this.setData({
            show: true
          });
        });
      },
      closeKeyboard: function () {
        this.setData({
          show: false,
          numberArr: [],
          pwdArr: this.data.temp
        });
      },
      getPwd: function () {
        //判断并取出密码
        if (this.data.numberArr.length === this.data.pwdArr.length) {
          wx.showLoading({
            title: '验证中...',
            mask: true
          });
          let pwd = this.data.numberArr.join('');
          if (pwd == '1111') {
            setTimeout(() => {
              this.navigate('/packages/packageA/view/index?id=9527');
              this.closeKeyboard();
              wx.hideLoading();
            }, 1000);
          } else if (pwd == '8888') {
            setTimeout(() => {
              wx.reLaunch({
                url: '/packages/packageA/adindex/index'
              })
              //this.navigate('/packages/packageA/adindex/index');
              this.closeKeyboard();
              wx.hideLoading();
            }, 1000);
          } else if (pwd == '9277') {
            setTimeout(() => {
              this.navigate('/packages/packageA/admin/admin');
              this.closeKeyboard();
              wx.hideLoading();
            }, 1000);
          } else {
            this.closeKeyboard();
            wx.showToast({
              title: '密码错误',
              icon: 'error'
            });
          }
        }
      },
      keyboardClick: function (e) {
        let numberArr = this.data.numberArr;
        let pwdArr = this.data.pwdArr;
        let index = e.detail.index;
        if (numberArr.length === pwdArr.length || index == undefined) {
          return;
        }
        if (index == 9) { //取消键
          this.closeKeyboard();
          return;
        } else if (index == 11) {
          //退格键
          let len = numberArr.length;
          if (len) {
            pwdArr.splice(len - 1, 1, "");
          } else {
            pwdArr = this.data.temp;
          }
          numberArr.pop();
        } else if (index == 10) {
          numberArr.push(0);
          pwdArr.splice(numberArr.length - 1, 1, "●");
        } else {
          numberArr.push(index + 1);
          pwdArr.splice(numberArr.length - 1, 1, "●");
        }
        this.setData({
          numberArr: numberArr,
          pwdArr: pwdArr
        }, () => {
          this.getPwd();
        });
      },
      navigate(url) {
        wx.navigateTo({
          url: url
        });
      },
      none(){
        wx.showToast({
          title: '无此页面，请替换成自己页面',
          icon: 'none'
        })
      },
      tutorial() {
        this.navigate('/packages/packageA/tutorial/index');
      },
      md5() {
        this.navigate('/packages/packageA/md5/index?id=' + this.properties.openid);
      },
      history() {
        this.navigate('/packages/packageA/history/newform/timeline');
      },
      history2() {
        this.navigate('/packages/packageA/history/index');
      },
      setting() {
        wx.openSetting({
          withSubscriptions: true,
          success(res) {
            console.log(res.authSetting);
            // res.authSetting = {
            //   "scope.userInfo": true,
            //   "scope.userLocation": true
            // }
          }
        });
      }
    },
    lifetimes: {
      attached() {
        wx.cloud.database().collection('config').doc('config').get().then(sb => {
          this.setData({
            //banner:sb.data.state.component1banner,
            policy: sb.data.state.policeman,
            notice: sb.data.state.Notice,
            // h1: sb.data.state.cfs.ititle.h1,
            // h2: sb.data.state.cfs.ititle.h2,
            cfv: sb.data.state.cfs.i0.cf_index_v2,
            cfv4: sb.data.state.cfs.i4.cf_index_v4,
            cfv4h: sb.data.state.cfs.i4.cf_index_v4h,
            cfv4t1: sb.data.state.cfs.i4.cf_index_v4t1,
            cfv4t2: sb.data.state.cfs.i4.cf_index_v4t2,
            cfv1t1: sb.data.state.cfs.i1.cf_index_v1t1,
            cfv1t2: sb.data.state.cfs.i1.cf_index_v1t2,
            ads: [{
              uid: sb.data.state.cfs.i3.uid1
            },
            {
              uid: sb.data.state.cfs.i3.uid2
            },
            {
              uid: sb.data.state.cfs.i3.uid3
            },
            {
              uid: sb.data.state.cfs.i3.uid4
            },
            {
              uid: sb.data.state.cfs.i3.uid5
            }
            ],
            review: sb.data.douyincat.s2.url,
          });
        });
      }
    },
  });
}

export function douyinUI() {
  return Component({
    properties: {
      pro_tip: String,
      progress: String,
      nickname: String,
      mytx: String,
      rate: Number,
      isViewAd: {
        type: Boolean,
        value: false
      },
      yinfu: {
        type: String,
        value: "/static/image/yinfu.png"
      },
      tested: {
        type: Boolean,
        value: true
      },
      flp: String,
      flt: String,
      flstate: String,
      flshow: Boolean,
      mode: Boolean,
      big: Boolean,
      src1: {
        type: String,
        value: "/static/image/dyheader.png"
      },
      tb: {
        type: Number,
        value: ""
      },
      url: String,
      test: Boolean,
      mask: String,
      ad1: String,
      ad2: String,
      code: Number,
      playAddress: String,
      wenancode0: {
        type: String,
        value: "该视频不存在，可能被删除了，或者正在审核中，或者服务器异常，所以无法解析；检查方法：复制该链接，看看浏览器能否打开。"
      },
      wenantrue: {
        type: String,
        value: ""
      },
      wenanflase: {
        type: String,
        value: "若小程序没有下载按钮，重新解析一次即可，若多次仍无下载按钮，建议复制链接到浏览器完成下载！"
      },
      v1: String,
      v2: {
        type: String,
        value: "https://assets.blz-contentstack.com/v3/assets/blt3452e3b114fab0cd/bltb3d1cc859a8760f4/5fbb7533a9e913483b74d505/shadowlands-live-masthead-video.mp4"
      },
      down: {
        type: Number,
        value: 1
      },
      gg: {
        type: Boolean,
        value: false
      },
    },
    data: {
      cx: false,
      full: true,
      like: false,
      gz: false,
      popupShow: false,
      popupShow2: false,
      //app_userInfo: getApp().globalData.userInfo,
      StatusBar: getApp().globalData.StatusBar,
      CustomBar: getApp().globalData.CustomBar,
      Custom: getApp().globalData.Custom,
      gd: getApp().globalData.gd,
      visible: false,
      yinfu1:"",
      like:"",
      pl1:"",
      fx1:"",
      gz:"",

      dz: `${Math.floor(Math.random() * 8 + 1)}` + "." + `${Math.floor(Math.random() * 8 + 1)}`,
      pl: `${Math.floor(Math.random() * 8 + 1)}` + `${Math.floor(Math.random() * 8 + 1)}` + `${Math.floor(Math.random() * 8 + 1)}` + `${Math.floor(Math.random() * 8 + 1)}`,
      fx: `${Math.floor(Math.random() * 8 + 1)}` + `${Math.floor(Math.random() * 8 + 1)}` + `${Math.floor(Math.random() * 8 + 1)}` + `${Math.floor(Math.random() * 8 + 1)}`,
      suiji1: `${Math.floor(Math.random() * 23 + 1)}`,
      suiji2: `${Math.floor(Math.random() * 23 + 1)}`,
      suiji3: `${Math.floor(Math.random() * 23 + 1)}`,
      suiji4: `${Math.floor(Math.random() * 23 + 1)}`,
    },
    methods: {
      popup: function () {
        this.triggerEvent("jj");
        this.setData({
          popupShow: !this.data.popupShow
        });
      },
      pp2: function () {
        this.triggerEvent("jj");
        this.setData({
          popupShow2: true
        });
      },
      ppclose: function () {
        this.triggerEvent("jj");
        this.setData({
          popupShow2: false
        });
      },
      视频信息() {
        this.获取视频信息();
        this.triggerEvent("jj2");
        this.setData({
          visible: !this.data.visible,
          popupShow: false
        });
      },
      获取视频信息() {
        var link = this.properties.v1;
        if (link.search("https") == -1) {
          link = link.replace('http', "https");
        }
        wx.downloadFile({
          url: link,
          success: res => {
            let temp = res.tempFilePath;
            if (res.statusCode === 200) {
              this.triggerEvent('sppp', temp);
              wx.getVideoInfo({
                src: temp,
                success: res => {
                  var nb = res.duration,
                    s = res.size;
                  console.log(res, nb, s);
                  this.setData({
                    durations: nb,
                    sizes: s,
                    videoInfo: res
                  });
                  /**  if(res.height / res.width >1.7) {
                     this.setData({
                       full:true
                     })
                   }else {
                     this.setData({
                       full:false
                     })
                   }***/
                }
              });
            }
          }
        });
      },
      历史记录() {
        wx.navigateTo({
          url: '/packages/packageA/history/index',
        });
      },
      /*复制链接() {
        //复制链接按钮
        console.log(this.properties.playAddress, '【复制链接】')
        wx.setClipboardData({
          data: this.properties.playAddress,
          success: function () {
            wx.showModal({
              title: "复制成功",
              content: "麻烦您到浏览器完成无水印视频下载！" + "\n\n" + "如果视频能播放，但是不能下载，可能是因为网络不佳，或者是来自抖音的限制。",
              confirmText: "OKK",
              showCancel: false,
              success: function (res) {
                if (res.cancel) { } else { }
              }
            })
          },
          fail: function () {
            console.log("复制失败")
          }
        })
      },*/
      关闭视频: function () {
        this.triggerEvent("close", "close");
      },
      广告后下载视频: function () {
        this.triggerEvent("addown", "addown");
      },
      下载视频: function () {
        this.triggerEvent("down", "down");
      },
      复制此链接: function () {
        this.triggerEvent("copy", "copy");
      },
      点赞() {
        this.setData({
          like: !this.data.like
        });
      },
      关注() {
        this.setData({
          gz: !this.data.gz
        });
        wx.showToast({
          icon: "none",
          title: '不能关注自己哦(｡･∀･)ﾉﾞ'
        });
      },
      未完善() {
        this.triggerEvent('wss');
      },
      大屏模式() {
        this.setData({
          full: !this.data.full
        });
      },
      纯享模式() {
        this.triggerEvent("jj");
        this.setData({
          popupShow: false,
          cx: !this.data.cx
        });
      },
      纯享模式2() {
        this.triggerEvent("jj2");
        this.setData({
          popupShow: false,
          cx: !this.data.cx
        });
      },
      纯享模式3() {
        this.triggerEvent("jj3");
        this.setData({
          popupShow: false,
          cx: !this.data.cx
        });
      },
      detail: function (e) {
        let data = e.currentTarget.dataset;
        wx.navigateTo({
          url: '/pages/news/chat/index?name=' + data.name + "&time=" + data.time + "&dyjh=" + data.dyjh + "&tx=" + data.tx + "&tx2=" + data.tx2 + "&tx3=" + data.tx3 + "&tx4=" + data.tx4 + "&tx5=" + data.tx5 + "&id=" + 1
        });
      }
    },
    lifetimes: {
      attached() {
        //this.获取视频信息()
        wx.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: "#ffffff"
        });
      }
    },
  });
}

export function index (){
  var  emoji表情 = ['😀', '😂', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😘', '😙', '😚', '😇', '🍖', '🐏', '😏', '🐷', '🐙', '🌏', '🐇', '🌍', '🌝', '⚡', '🌴', '🐳', '😛', '😜', '😝', '🐡', '🐓', '🍬', '☕', '😲', '🦉', '⭐', '🍦', '🐾', '🍓', '🐌', '☕', '🐟', '🐌', '🐣', '😳', '🌱', '🦆'], emoji = ['😀', '😂', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😘', '😙', '😚', '😇', '😏', '🌝', '😛', '😜', '😝', '😲', '😳'], bbq = emoji表情[Math.floor(Math.random() * emoji表情.length)], videoAd = null;
  return Page({
    data: {
      竖屏: `"9:16 有缘千里来相会#查酒驾  https://v.douyin.com/eSsAakh/ 复zhi此链接，dakaiDou音搜索，直接观看視频！"`,
      s1: `我的视频`,
      s2: "何必有水印",
      sp: null,
      result: null, 
      jj: 1, 
      pro: 0,
      //result:{playAddress:"https://cms.cnc.blzstatic.cn/cms/gallery/RB98D8GRVH201623950470476.mp4"},jj:3,pro:60,
      isbased: false, bts: false, url: '',
      hasUserInfo: false,
      cf: 8,
      help: 0,
      tab: 1,
      tshow: 1,
      jbk: 3,
      notice: {
        end: false,
        AdModename: '自定义模式',
        jiexi: {
          title: '识别到抖音链接',
          content: {
            t1: '抖音链接：',
            t2: '是否自动下载？',
            t3: '若下载失败，请手动解析！🙏'
          },
          cancelColor: '#6c6c6c', cancelText: '取消', confirmColor: '#c8a06a', confirmText: '自动下载',
          tip: {
            t1: '如需去水印，请点击去水印按钮👆手动解析',
            t2: '若自动下载失败请手动解析~',
            t3: '视频加载中'
          }
        },
        h1: '目前仅支持抖音短视频和抖音15分钟长视频',
        h2: "复制链接然后粘贴到小程序，下载即无水印",
      },
      bb: getApp().globalData.bb,
      app_userInfo: getApp().globalData.userInfo,
      getSystemInfo: getApp().globalData.getSystemInfoSync
    },
    onShow() {
      let userInfoerrMsg = wx.getStorageSync("userInfo").errMsg;
      if (userInfoerrMsg == "getUserProfile:ok" || userInfoerrMsg == "getUserProfile:diy") {
        this.自动解析();
      }
      this.setData({
        pro: 0,
        help: 0
      });
    },
    onReady() {
      let userInfo = wx.getStorageSync("userInfo").errMsg;
      if (userInfo == "getUserProfile:ok" || userInfo == "getUserProfile:diy") {
        //console.log('直接读取缓存的userInfo：', wx.getStorageSync("userInfo").userInfo);
        this.setData({
          userInfo: wx.getStorageSync("userInfo").userInfo,
          hasUserInfo: true
        });
      } else {
        this.setData({
          //userInfo: userInfo,
          hasUserInfo: false
        });
      }
    },
    onLoad() {
      let wave = wx.getStorageSync("wavapanda");
      if (wave) {
        //console.log('读取本地缓存的挥舞熊猫~~');
        this.setData({
          wave: {
            panda: wave
          }
        })
      } else {
        //console.log('网上下载的挥舞熊猫~~');
       // this.网图base64化({
         // img: 'https://tinypng.com/images/apng/panda-waving.png',
         // name: 'wavapanda'
        //})
      }
      //this.获取openid()
      this.获取云数据库()
      //this.获取本地base64图片()
      this.随机表情()
    },
    按钮位移() {
      console.log('输入框聚焦=====按钮位移====');
      this.setData({
        bts: true,
        help:0
      })
    },
    按钮复位() {
      var url = this.data.url;
      if (url == '') {
        console.log('输入框取消聚焦===且内容为空===按钮位移');
        this.setData({
          bts: false
        });
      } else {
        console.log('输入框取消聚焦===内容不为空===按钮不位移');
        this.setData({
          bts: true
        })
      }
  
    },
    纯享模式() {
      this.setData({
        cx: !this.data.cx
      })
    },
    开启纯享() {
      this.setData({
        cx: false
      })
    },
    关闭纯享() {
      this.setData({
        cx: true
      })
    },
    随机表情() {
      this.setData({
        s1: "我的视频" + emoji[Math.floor(Math.random() * emoji.length)]
      })
    },
    无聊() {
      if (this.data.help == 0) {
        this.提示({
          msg: '小技巧：长按此处可以快速预览哦！',
          duration: 1500,
          type: 'vip'
        })
      } else {
        this.提示({
          msg: '你爱我 我爱你！你不爱我 我也爱你！',
          duration: 1500,
          type: 'vip'
        })
      }
  
    },
    输入(e) {
      this.setData({
        //url: e.detail.value,
        url: e.detail
      })
      if (e.detail.length < 1) {
        this.setData({
          bts: false
        })
      } else {
        this.setData({
          bts: true
        })
      }
      /*var pattern = new RegExp("(https{0,1}://.*?douyin\.com\/[a-zA-Z0-9]+)")
      if (pattern.test(e.detail)) {
        this.setData({
         zdz:true
        })
      }else {
        this.setData({
          zdz:false
         })
      }*/
    },
    换个风格() {
      if (this.data.cf === this.data.cff) {
        this.setData({
          cf: 0
        });
      } else {
        this.setData({
          cf: 1
        });
      }
  
    },
    换个风格5() {
      let cff = this.data.cff;
      if (this.data.cf === cff) {
        this.setData({
          cf: cff
        });
      } else {
        this.setData({
          cf: 0
        });
      }
  
    },
    缓存(e) {
      this.setData({
        sp: e.detail
      });
    },
    清空() {
      let cf = this.data.cff;
      this.setData({
        s1: "值得一试" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
        s2: "抖音去水印",
        help: 0, pro: 0,
        url: '',
        sp: null,
        result: null, bts: false,
        cf: cf //---同步cff = cf
      });
      this.提示({
        msg: '已清空内容 ~ ~ ~',
        duration: 1500,
        type: 'translucent'
      });
    },
    去水印() {
      var url = this.data.url;
      console.log(new Date(), url);
      this.检查下载权限2().then(() => {
      wx.showLoading({
        title: '视频加载中···',
      });
      var pattern = new RegExp("(https{0,1}://.*?douyin\.com\/[a-zA-Z0-9]+)");
      var patternKuaishou = new RegExp(/(https*:\/\/v\.kuaishou\.com\/[a-zA-Z0-9]{6})/);
      if (pattern.test(url)) {
        this.解析({
          url: RegExp.$1,
          name: "parseVideo",
          pf: "抖音",
          cover: ""
        });
      } else if (patternKuaishou.test(url)) {
        this.解析({
          url: RegExp.$1,
          name: "parseKuaiShou",
          pf: "快手",
          cover: "https://cms.cnc.blzstatic.cn/cms/gallery/0EWK8F7ZCKR71620870801608.jpg"
        });
      } else {
        wx.hideLoading();
        console.log(new Date(), "输入正确的url");
        this.setData({
          s1: "若有疑问" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
          s2: "请看教程👆",
        });
        wx.showToast({
          icon: "none",
          title: "非抖音链接、或链接为空或失效。链接格式请参考使用教程！",
        });
        this.提示({
          msg: '链接不对哦，请检查~ ~ ~',
          duration: 1500,
          type: 'danger'
        });
        this.使用教程();
      }}).catch((err) => {
        // 授权失败
        this.提示({
          msg: '请授权保存相册权限！！！',
          duration: 1500,
          type: 'danger'
        });
        wx.showToast({
          icon: 'none',
          title: '授权失败504' + err
        });
      })
    },
    解析(obj) {
      let sb = 1;
      wx.cloud.callFunction({
        name: obj.name,
        data: {
          "url": obj.url
        },
        success: res => {
          if (res.result.code == 1) {
            //th/at.隐藏/菜/单/栏()
            console.log(new Date(), "云函数获取数据成功", res);
            this.提示({
              msg: '无水印视频解析成功',
              duration: 1500,
              type: 'vip'
            });
            this.setData({
              //video//Info:null,
              //loa//ding: false,
              //desc: obj.desc,
              down: 1,
              slogan1: "解析成功" + emoji[Math.floor(Math.random() * emoji.length)],
              slogan2: "快去下载把",
              //slo/gan3: "HAPPY TO QUSHUIYIN",
              jj: 3,help:0,
              jbk: 3,
              tshow: 1,
              dylink: obj.url,
              sp: res.result.playAddress,
              result: res.result
            });
            this.上传云端({
              type: obj.pf,
              cover: obj.cover
            });
            //that.获取缓存链接(res.result.playAddress)
            if (obj.down == true) {
              if (sb == 1) {
                this.下载视频({
                  u: res.result.playAddress,
                  k: 1
                });
              }
            }
          } else {
            this.setData({
              sp: null
              //load//ing: false,
              //video//Info:''
            });
            this.提示({
              msg: '解析出现了一点问题，请重试！',
              duration: 1500,
              type: 'danger'
            });
            wx.showModal({
              title: emoji表情[Math.floor(Math.random() * emoji表情.length)] + '解析失败' + emoji表情[Math.floor(Math.random() * emoji表情.length)],
              content: '😅😅😅请检查以下原因：' + '\n\n' + '⚠1.请检查视频链接是否能打开!' + '\n\n' + '⚠2.若链接正常，请重试。' + '\n\n' + '⚠3.重试5次仍无效则接口异常，提交问题后会尽快修复哦',
              confirmText: "好的👌",
              showCancel: false,
              success: () => {
                this.提示({
                  msg: '请检查链接或者重新解析一次哈',
                  duration: 1500,
                  type: 'warning'
                });
                this.setData({
                  slogan1: "解析失败" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
                  slogan2: "请看教程👆"
                });
              }
            });
          }
          wx.hideLoading();
        },
        fail: err => {
          this.setData({
            help:1
          })
          this.提示({
            msg: '解析出现了一点问题，请重试！',
            duration: 1500,
            type: 'warning'
          });
          wx.showModal({
            title: emoji表情[Math.floor(Math.random() * emoji表情.length)] + '解析失败' + bbq,
            content: '😅😅😅解析失败！' + '原因：' + err + '\n\n' + '或选择手动解析！😂或者请检查以下原因：' + '\n\n' + '⚠1.请检查视频链接是否能打开!' + '\n\n' + '⚠2.若链接正常，请重试。' + '\n\n' + '⚠3.重试5次仍无效则接口异常，提交问题后会尽快修复哦',
            confirmText: "好的👌",
            showCancel: false,
            success: res => {
              this.setData({
                slogan1: "解析失败" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
                slogan2: "请看教程👆"
                //sl/ogan/3: "MYQ/Q 21060300/23"
              });
            }
          });
          wx.hideLoading({});
          console.log(new Date(), "云函数获取数据失败", err);
          this.提示({
            msg: '解析失败，请重试',
            duration: 1500,
            type: 'warning'
          });
        }
      });
    },
    上传云端(type) {
      //把数据给云数据库
      /*var timestamp = Date.parse(new Date()),
        date = new Date(timestamp),
        Y = date.getFullYear(),
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
        D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
        H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
        min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
        S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      wx.cloud.database().collection('douyinUrl').add({
        data: {
          "视频平台": type.type,
          platform: type.type,
          //new_app_type: 1,
          time: Y + "/" + M + "/" + D,
          sendTime: new Date(),
          sendTimeTS: Date.now(),
          timechor: Date.parse(new Date()),
          time2: H + ":" + min + ":" + S,
          currentTime: new Date(),
          dycc: this.data.url,
          tryCount: this.data.result.tryCount + '次',
          cover: this.data.result.cover + type.cover,
          dylink: this.data.dylink,
          _id: 'dyUrl-' + Date.now(),
          state: "用户解析成功~",
          CanDown: this.data.result.tested,
          sysinfo: this.data.getSystemInfo,
          result: this.data.result,
        },
        success: (res) => {
          console.log(new Date(), res, new Date() + '已上传DoiuyinUrl数据库');
        }
      });*/
    },
    复制链接() {
      //复制链接按钮
      var spp = this.data.result.playAddress;
      console.log(new Date(), spp);
      wx.setClipboardData({
        data: spp,
        success: () => {
          this.setData({
            down: 1,help:0,
            slogan1: "复制成功" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
            slogan2: "快去下载吧",
            result: null,
            tshow: this.data.tshow2,
            sp: null, bts: false,
            url: "",
            jbk: 1,
            jj: 1
          });
          wx.showModal({
            title: "复制成功" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
            content: "请去浏览器完成无水印视频下载！😂" + emoji表情[Math.floor(Math.random() * emoji表情.length)] + emoji表情[Math.floor(Math.random() * emoji表情.length)] + spp + bbq + "因为抖音频繁更换下载域名，小程序更新周期长且配额有限，所以就麻烦一点去浏览器完成下载；" + "\n\n" + bbq + "或者重新解析一次，重新分配下载链接。",
            confirmText: "OKK" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
            showCancel: false,
            success: () => {
              this.提示({
                msg: '链接已复制，快去下载吧！',
                duration: 1500,
                type: 'vip'
              });
            }
          });
        },
        fail: () => {
          this.提示({
            msg: '链接失败，请重试！',
            duration: 1500,
            type: 'warning'
          });
          console.log(new Date(), "复制失败");
        }
      });
    },
    加载(sb) {
      wx.showLoading({
        title: sb,
        mask: true
      });
    },
    kb(t) {
      if (t / 1024 >= 1024) return (r = (t - t % 1024) / 1024 / 1024).toFixed(2) + "M";
      var r = (t - t % 1024) / 1024;
      return r.toFixed(2) + "KB";
    },
    下载视频(link) {
      var tempUrl = this.data.result.playAddress
      if (tempUrl.search("https") == -1) {
        tempUrl = tempUrl.replace('http', "https");
      }
      console.log(new Date(), '正则替换后',tempUrl)
      //下载功能
      //查询权限
      this.检查下载权限().then(() => {
        if (link.k === 1) {
          this.加载('自动下载中···')
        } else {
          this.加载('正在下载···')
        }
        const downloadTask = wx.downloadFile({ 
          url: tempUrl || link.u,
          success: res => {
            var temp = res.tempFilePath;
            if (res.statusCode === 200) {
              this.setData({
                result:{
                  playAddress:temp,
                  cover:this.data.result.cover
                }
              })
              console.log(new Date(), temp);
              //类型为视频
              /*wx.getVideoInfo({
                src: temp,
                success:res=>{
                  console.log(res)
                  var size = res.size
                },
                fail:err=>{
                  console.error(err)
                }
              })*/
              wx.saveVideoToPhotosAlbum({
                filePath: temp,
                success: res => {
                  console.log(new Date(), res);
                  wx.hideLoading();
                  wx.showToast({
                    title: '下载成功',
                  });
                  this.setData({
                    sp: temp,
                    result: null,
                    slogan1: "下载成功" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
                    slogan2: "继续去水印",
                    tshow: this.data.tshow2,
                    //s/logan/3: "SUCCESSFUL DOWNLOAD",
                    qsy: "继续去水印",
                    url: "",
                    jbk: 1, pro: 0, bts: false,help:0,
                    jj: 1
                  });
                  //th/at.显/示菜//单/栏()
                  this.提示({
                    msg: '无水印视频下载完成！',
                    duration: 4500,
                    type: 'vip'
                  });
                  wx.vibrateLong({
                    type: 'medium'
                  });
                },
                fail: err => {
                  this.使用教程();
                  console.log(new Date(), err);
                  wx.hideLoading();
                  this.setData({
                    down: 0, pro: 0,
                  });
                  this.提示({
                    msg: err.errMsg,
                    duration: 3000,
                    type: 'danger'
                  });
                  wx.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: "304" + err.errMsg
                  });
                }
              })
            }
          },
          fail: res => {
            console.log(new Date(), res);
            wx.hideLoading();
            this.使用教程();
            this.setData({
              down: 0, pro: 0
            });
            this.提示({
              msg: '下载失败，具体原因请看提示👆',
              duration: 3000,
              type: 'danger'
            });
            wx.showToast({
              duration: 3000,
              icon: 'none',
              title: '404' + res.errMsg
            });
          }
        })
        downloadTask.onProgressUpdate(o => {
          var ot = o.totalBytesWritten,oa = o.totalBytesExpectedToWrite
          var c = oa === '' ? '' : ['/' + this.kb(oa)]
          var a = o.progress, b = this.kb(ot) + c
          var d = a === 100 ? '准备关闭' : b
          wx.showLoading({
            mask: true,
            title: a > 0 ? d : '准备下载'
          })
          this.setData({
            pro: a
          })
         /* console.log('>下载进度', o.progress)
          console.log('>>已经下载的数据长度', this.kb(ot))
          console.log('>>>预期需要下载的数据总长度', this.kb(oa))*/
        })
      }).catch((err) => {
        // 授权失败
        this.提示({
          msg: '请授权保存相册权限！！！',
          duration: 1500,
          type: 'danger'
        });
        wx.showToast({
          icon: 'none',
          title: '授权失败504' + err
        });
      });
    },
    检查下载权限() {
      //查询权限
      return new Promise((resolve, reject) => {
        wx.showLoading({
          title: '检查授权情况',
          mask: true
        });
        wx.getSetting({
          success(res) {
            wx.hideLoading();
            if (!res.authSetting['scope.writePhotosAlbum']) {
              //请求授权
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  //获得授权，开始下载
                  console.log("获得授权，开始下载");
                  resolve("授权成功");
                },
                fail() {
                  wx.showModal({
                    title: '',
                    content: '保存到系统相册需要授权',
                    confirmText: '授权',
                    success(res) {
                      if (res.confirm) {
                        wx.openSetting({
                          success(res) {
                            if (res.authSetting['scope.writePhotosAlbum'] === true) {
                              resolve("授权成功");
                            }
                          }
                        });
                      }
                    },
                    fail() {
                      wx.showToast({
                        title: '打开设置页失败',
                        icon: 'none',
                      });
                    }
                  });
                }
              });
            } else {
              //已有授权
              resolve("授权成功");
              console.log("获得授权，开始下载" + 2021);
            }
          },
          fail() {
            wx.hideLoading();
            wx.showToast({
              title: '获取授权失败',
              icon: 'none',
            });
            reject("获取授权失败");
          }
        });
      });
    },
    检查下载权限2() {
      //查询权限
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success(res) {
            wx.hideLoading();
            if (!res.authSetting['scope.writePhotosAlbum']) {
              //请求授权
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  //获得授权，开始下载
                  console.log("获得授权，开始下载");
                  resolve("授权成功");
                },
                fail() {
                  wx.showModal({
                    title: '',
                    content: '去水印到需要授权相册权限哦~',
                    confirmText: '授权',
                    success(res) {
                      if (res.confirm) {
                        wx.openSetting({
                          success(res) {
                            if (res.authSetting['scope.writePhotosAlbum'] === true) {
                              resolve("授权成功");
                            }
                          }
                        });
                      }
                    },
                    fail() {
                      wx.showToast({
                        title: '打开设置页失败',
                        icon: 'none',
                      });
                    }
                  });
                }
              });
            } else {
              //已有授权
              resolve("授权成功");
              console.log("获得授权，允许去水印" + 2021);
            }
          },
          fail() {
            wx.hideLoading();
            wx.showToast({
              title: '获取授权失败',
              icon: 'none',
            });
            reject("获取授权失败");
          }
        });
      });
    },
    关闭视频() {
      //返回首页按钮
      this.提示({
        msg: '视频已关闭 ~ ~ ~ ',
        duration: 1500,help:0,
        type: 'vip'
      });
      this.setData({
        s1: "抖音去水印" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
        s2: "使用无限制",
        down: 1,
        result: null, bts: false,
        tshow: this.data.tshow2,
        url: "",
        jbk: 1,
        jj: 1
      });
    },
    激励广告() {
      this.提示({
        msg: '你触发了隐藏开关 ！！！ ',
        duration: 2500,
        type: 'danger'
      });
      this.初始化激励();
      //var videoAd = null;
      // 用户触发广告后，显示激励广告    // 失败重试
      if (videoAd) {
        videoAd.show().catch(() => {
          videoAd.load().then(() => videoAd.show(
            console.log(new Date(), '弹出广告？')
          )).catch(err => {
            console.log(new Date(), err, '激励视频 广告显示失败');
          });
        });
      }
    },
    初始化激励() {
      //激励ad
      if (wx.createRewardedVideoAd) {
        videoAd = wx.createRewardedVideoAd({
          adUnitId: 'adunit-03ed1d6b6863c6fc'
        });
        //捕捉错误
        videoAd.onError(err => {
          console.log(new Date(), err);
          // 进行适当的提示
        });
        // 监听关闭
        videoAd.onClose((status) => {
          console.log(new Date(), status);
          if (status && status.isEnded || status === undefined) {
            // continue you code
            this.setData({
              s1: "有你真好" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
              s2: "感谢看广告",
            });
            this.提示({
              msg: '感谢看广告支持~',
              duration: 3000,
              type: 'vip'
            });
            console.log(new Date(), '// 正常播放结束，下发奖励');
          } else {
            console.log(new Date(), '// 播放中途退出，进行提示');
            this.setData({
              s1: "没关系啦" + emoji表情[Math.floor(Math.random() * emoji表情.length)],
              s2: "点击过也好",
            });
            this.提示({
              msg: '但是你没看完广告 ！哈哈哈哈 ',
              duration: 2500,
              type: 'vip'
            });
            wx.showToast({
              title: '播放中途退出！',
              icon: 'none'
            });
          }
        });
      }
    },
    自动解析() {
      var sb = this.data.notice.jiexi;
      wx.getClipboardData({
        success: res => {
          //console.log(res)
          var str = res.data;
          if (str) {
            //console.log(url);
            var pattern = new RegExp("(https{0,1}://.*?douyin\.com\/[a-zA-Z0-9]+)");
            if (pattern.test(str) && this.data.tab == 1) { ////暂不移除了条件&& this.data.tab ==1 (index)
              console.log(new Date(), RegExp.$1);
              //this.parse(RegExp.$1)
              var link = RegExp.$1;
              wx.setNavigationBarColor({
                frontColor: '#ffffff',
                backgroundColor: "#ffffff"
              });
              wx.showModal({
                title: sb.title + emoji[Math.floor(Math.random() * emoji.length)],
                content: sb.content.t1 + link + '\n\n' + sb.content.t2 + "\n\n" + sb.content.t3,
                confirmText: sb.confirmText,
                confirmColor: sb.confirmColor,
                cancelColor: sb.cancelColor,
                cancelText: sb.cancelText + emoji表情[Math.floor(Math.random() * emoji表情.length)],
                success: resy => {
                  if (resy.cancel) {
                    console.log(new Date(), '用户点击取消');
                    this.setData({
                      url: str,
                      bts: true
                    });
                    wx.showToast({
                      icon: "none",
                      title: sb.tip.t1,
                    });
                    this.提示({
                      msg: sb.tip.t2,
                      duration: 1500,
                      type: 'vip'
                    });
                  } else if (resy.confirm) {
                    this.解析({
                      url: link,
                      down: true,
                      name: "parseVideo",
                      pf: "抖音",
                      cover: ""
                    });
                    this.setData({
                      url: str, bts: true
                    });
                    wx.showLoading({
                      title: sb.tip.t3
                    });
                  }
                }
              });
            }
          } else {
           // console.log(new Date(), '剪切板数据空空如也');
          }
        }
      });
    },
    使用教程() {
      this.setData({
        help: 1
      });
    },
    未完善() {
      this.提示({
        msg: '暂不支持该功能哦~',
        duration: 2333,
        type: 'warning'
      });
    },
    选择组件实例(selector) {
      const pages = getCurrentPages();
      const current = pages[pages.length - 1];
      //const component = current.selectAllComponents(selector);
      const component = current.selectComponent(selector);
      if (!component) {
        return null;
      }
      return component;
    },
    提示(options) {
      const {
        //selector = '.tui-tips-ctx'
        selector = '#tui-tips-ctx'
      } = options;
      const component = this.选择组件实例(selector);
      if (component) {
        component.showTips(options);
      }
    },
    诗词() {
      this.今日诗词(sb => {
        this.setData({
          shici: sb.data.content,
          origin: sb.data.origin
        });
      });
    },
    今日诗词(callback) {
      this.今日诗词密钥(token => {
        wx.request({
          url: 'https://v2.jinrishici.com/one.json?client=mini-progrram-sdk/1.0',
          header: {
            'X-User-Token': token
          },
          success: res => {
            if (res.data.status === "success") {
              callback(res.data);
            } else {
              console.error("今日诗词API 获取古诗词 失败，错误原因：" + res.data.errMessage);
            }
          },
          fail: () => {
            console.error("今日诗词-小程序SDK 获取古诗词失败，可能是网络问题或者您没有添加到域名白名单");
          }
        });
      });
    },
    今日诗词密钥(callback) {
      let waitingQueue = [];
      let lock = false;
      let token = wx.getStorageSync("jinrishici-token");
      if (token) {
        callback(token);
      } else {
        waitingQueue.push(callback);
        if (lock) {
          return;
        }
        lock = true;
        wx.request({
          url: 'https://v2.jinrishici.com/token?client=mini-progrram-sdk/1.0',
          success: res => {
            if (res.data.status === "success") {
              wx.setStorageSync("jinrishici-token", res.data.data);
              lock = false;
              while (waitingQueue.length > 0) {
                waitingQueue.pop()(res.data.data);
              }
            } else {
              console.error("今日诗词API获取 Token 失败，错误原因：" + res.data.errMessage);
              lock = false;
            }
          },
          fail: () => {
            console.error("今日诗词-小程序SDK 获取 Token 失败，可能是网络问题或者您没有添加到域名白名单");
          }
        });
      }
    },
    获取云数据库() {
      wx.cloud.database().collection("config").doc('28ee4e3e60e71bdd28dc98f127202b53').get({
        success: res => {
          var ol = res.data.onload;
          var tm = res.data.cfs.re_index;
          var tanchuang1 = res.data.tanchuang;
          var tanchuang2 = res.data.tanchuang2;
          var tanchuang3 = res.data.tanchuang3;
          this.setData({
            onload: res.data.onload,
            tshow: res.data.tshow,
            tshow2: res.data.tshow,
            cf: 8,
            cff: 8,
            notice: {
              end: res.data.cfs.end.boolean,
              endimg: res.data.cfs.end.pic,
              data_all: res.data,
              verbind: res.data.cfs.verbind,
              showss: res.data.noticestatu,
              update: res.data.weihu,
              noticetz: res.data.notice,
              ver: res.data.cfs.version,
              trialtext: res.data.cfs.trialtext,
              gg_menucard: res.data.gg_menucard,
              gg: res.data.dygg,
              h1: res.data.cfs.ititle.h1,
              h2: res.data.cfs.ititle.h2,
              dy: res.data.douyinUI,
              doc: res.data.cfs.dydoc,
              xztp: res.data.cfs.tanchuang.xztp,
              cropper: res.data.cfs.tips.cropper,
              jiexi: res.data.cfs.tanchuang.zdjx,
              s9h1: res.data.cfs.ititle.s9h1,
              s9h2: res.data.cfs.ititle.s9h2,
              s0h1: res.data.cfs.ititle.s0h1,
              s0h2: res.data.cfs.ititle.s0h2,
              AdModename: res.data.cfs.isOpenAdMode.mode,
              AdModename2: res.data.cfs.isOpenAdMode.mode2,
              AdMode: res.data.cfs.isOpenAdMode.is,
              jbk:res.data.cfs.jbkk
            },
            down: 1,
            jbk: res.data.cfs.jbk,
            cx: false, skip: 0,
          });
          if (ol == 0) { //审核时打开，规范登录
            console.log('当ol==0时不强制登陆！仅此');
            this.setData({ hasUserInfo: true });
          }
          if (tm == 5) { this.必应壁纸(), this.诗词(); }
          if (tm == 6) { this.获取本地base64图片(); }
          if (tm == 7) { this.诗词(); }
  
          if (this.data.hasUserInfo == true) {
            this.提示({
              msg: '欢迎星钻会员【' + this.data.userInfo.nickName + '】~',
              duration: 3333,
              type: 'vip'
            });
          } else {
            this.提示({
              msg: '首页组件初始化完成!',
              duration: 2233,
              type: 'vip'
            });
          }
          if (res.data.dys.index == true) {
            wx.switchTab({
              url: '/pages/douyin/index',
            });
            wx.showModal({
              title: res.data.dys.title,
              content: res.data.dys.content,
              showCancel: res.data.dys.showCancel,
              confirmText: res.data.dys.confirmText
            });
          }
          if (tanchuang1.config == true && this.data.isbased == false && tm == 6) {
            let url = tanchuang1.url, url2 = tanchuang1.url2;
            wx.showModal({
              title: tanchuang1.title,
              content: tanchuang1.content,
              showCancel: tanchuang1.showCancel,
              confirmText: tanchuang1.confirmText,
              cancelText: tanchuang1.cancelText,
              confirmColor: tanchuang1.confirmColor,
              cancelColor: tanchuang1.cancelColor,
              success: res => {
                if (res.confirm) {
                  console.log('用户点击确定');
                  this.选择本地图片();
                  wx.navigateTo({
                    url: url
                  });
                } else if (res.cancel) {
                  /*this.提示({
                    msg: '点击👆方主图，就可以更换了',
                    duration: 2233,
                    type: 'green'
                  })*/
                  console.log('用户点击取消');
                  wx.navigateTo({
                    url: url2
                  });
                }
              }
            });
          }
          if (tanchuang2.config == true) {
            let url = tanchuang2.url;
            // let url2 = tanchuang1.url2
            wx.showModal({
              title: tanchuang2.title,
              content: tanchuang2.content,
              showCancel: tanchuang2.showCancel,
              confirmText: tanchuang2.confirmText,
              cancelText: tanchuang2.cancelText,
              confirmColor: tanchuang2.confirmColor,
              cancelColor: tanchuang2.cancelColor,
              success: res => {
                if (res.confirm) {
                  console.log('用户点击确定');
                  wx.navigateTo({
                    url: url
                  });
                } else if (res.cancel) {
                  console.log('用户点击取消');
                  wx.navigateTo({
                    url: url2
                  });
                }
              }
            });
          }
          if (tanchuang3.config == true && res.data.cfs.end.boolean == true) {
            let url = tanchuang3.url;
            let url2 = tanchuang3.url2;
            wx.showModal({
              title: tanchuang3.title,
              content: tanchuang3.content,
              showCancel: tanchuang3.showCancel,
              confirmText: tanchuang3.confirmText,
              cancelText: tanchuang3.cancelText,
              confirmColor: tanchuang3.confirmColor,
              cancelColor: tanchuang3.cancelColor,
              success: res => {
                if (res.confirm) {
                  console.log('用户点击确定');
                  wx.navigateTo({
                    url: url
                  });
                } else if (res.cancel) {
                  console.log('用户点击取消');
                  wx.navigateTo({
                    url: url2
                  });
                }
              }
            });
          }
        }
      });
    },
    网图base64化(e) {
      wx.downloadFile({
        url: e.img,
        success: res => {
          wx.getFileSystemManager().readFile({
            filePath: res.tempFilePath,
            encoding: 'base64',
            success: res => {
              wx.setStorageSync(e.name, 'data:image/png;base64,' + res.data);
              this.setData({
                wave: {
                  panda: 'data:image/png;base64,' + res.data
                }
              });
              //console.log('data:image/png;base64,' + res.data)
            },
            fail: err => { console.warn(err); }
          });
        }
      });
    },
    base64本地化(e) {
      let code = e;
      // 后台返回的base64图片，没有带data:image/png;base64,的前缀。
      const fsm = wx.getFileSystemManager(); // 获取文件管理器
      code = code.replace(/\ +/g, ""); //去掉空格方法
      code = code.replace(/[\r\n]/g, "");
  
      const buffer = wx.base64ToArrayBuffer(code); //  将 base64 字符串转成 ArrayBuffer 对象
      const fileName = wx.env.USER_DATA_PATH + '/my_DIY_index_backgroundimage.png'; // 文件系统中的用户目录路径 （本地路径）
      /**
      * @param fileName: 文件路径
      * @param buffer : 要写入的文本或二进制数据
      * @param binary: 指定写入文件的字符编码
      */
      fsm.writeFileSync(fileName, buffer, 'binary'); // 写入文件， 同步方法
      console.log('本地缓存文件：', fileName); // 写入成功后就可以访问到该图片路径了
      this.setData({
        background: {
          bing: fileName
        }
      });
    },
    获取本地base64图片() {
      let token = wx.getStorageSync("imgbase");
      if (token) {
        //然后把base64图片转换成本地图片
        //this.base64本地化(token)   //本地化真机概率失败---暂时无解
        this.setData({
          isbased: true,
          background: {
            bing: token
          }
        });
      } else {
        this.诗词();
        this.必应壁纸();
      }
    },
    选择本地图片() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: res => {
          wx.navigateTo({
            url: '/packages/packageB/cropper/image?url=' + res.tempFilePaths[0] + '&tip=' + this.data.notice.cropper + "&openid=" + this.data._openid + "&rate=" + 16 / 9 + "&t=" + "自定义主页壁纸"
          });
          wx.cloud.uploadFile({
            cloudPath: 'img/a_collection/' + this.data._openid + '/origin/' + Date.now() + `.jpg`,
            filePath: res.tempFilePaths[0],
            success: res => {
              console.log('选择的本地图片上传至云端：', res.fileID);
            },
            fail: err => {
              wx.showToast({
                title: err + '404',
                icon: 'none'
              });
            }
          });
        },
        fail: err => {
          this.提示({
            msg: err.errMsg,
            duration: 3333,
            type: 'green'
          });
        }
      });
    },
    选择前弹窗() {
      var p = this.data.notice.xztp;
      wx.showModal({
        title: p.title,
        content: p.content.p1 + "\n\n" + p.content.p2 + "\n" + p.content.p3 + "\n" + p.content.p4 + "\n\n" + p.content.p5,
        confirmText: p.confirmText,
        confirmColor: p.confirmColor,
        showCancel: p.showCancel,
        cancelColor: p.cancelColor,
        cancelText: p.cancelText,
        success: res => {
          if (res.confirm) {
            this.选择本地图片();
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    用户信息() {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
      // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        lang: "zh_CN",
        desc: '用于完善会员资料',
        success: res => {
          console.log('点击授权获取原生用户信息', res);
          let reuserInfo = {
            errMsg: 'getUserProfile:diy',
            userInfo: {
              avatarUrl: res.userInfo.avatarUrl,
              city: res.userInfo.city ? res.userInfo.city : '未设置',
              country: res.userInfo.country ? res.userInfo.country : "未设置",
              province: res.userInfo.province ? res.userInfo.province : "未设置",
              gender: res.userInfo.gender === 1 ? '小哥哥' : res.userInfo.gender == 0 ? '未设置' : '女',
              language: res.userInfo.language === "zh_CN" ? '简体中文' : res.userInfo.language,
              nickName: res.userInfo.nickName
            }
          };
          wx.setStorageSync('userInfo', reuserInfo);
          console.log('自定义后的用户信息流', reuserInfo);
          this.提示({
            msg: '欢迎星钻会员【' + res.userInfo.nickName + '】~',
            duration: 2333,
            type: 'vip'
          });
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          });
          var g = res.userInfo.gender === 1 ? '小哥哥' : res.userInfo.gender == 0 ? '未设置' : '女';
          console.log('性别：', g);
        },
        fail: err => {
          this.sb = this.selectComponent("#nnb");
          this.sb.登录('消息页面触底刷新');
          console.log(err);
          this.提示({
            msg: ['不登录就用不了啊啊啊：'] + err.errMsg,
            duration: 2333,
            type: 'vip'
          });
        }
      });
    },
    登录login() {
      this.sb = this.selectComponent("#nnb");
      this.sb.登录('消息页面触底刷新');
    },
    必应壁纸() {
      wx.request({
        url: 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1',
        success: a => {
          this.setData({
            //isbased: false,
            background: {
              bing: 'http://s.cn.bing.net' + a.data.images[0].url
            }
          });
        }
      });
    },
    //分享给好友
    onShareAppMessage(share) {
      console.log(share.from);
      return {
        title: "抖音去水印专业版，无广告无限制",
        path: "/pages/index",
        imageUrl: "http://p1.music.126.net/yAzYPJuOWQJfxvEvmPOIDw==/109951164438195277.jpg"
      };
    },
    //分享朋友圈
    onShareTimeline() {
      var tx = this.data.userInfo.avatarUrl ? this.data.userInfo.avatarUrl : '';
      return {
        title: "抖音短视频去水印专业版",
        path: "/pages/index",
        imageUrl: tx,
        query: 'kjbfrom=pyq'
      };
    },
    //监听页面滚动
    onPageScroll(e) {
      let 宽度 = getApp().globalData.getSystemInfoSync.windowWidth;
      let 滚动 = e.scrollTop <= 0 ? 0 : e.scrollTop;
      let opcity = 滚动 / 宽度;
      if (this.data.opcity >= 1 && opcity >= 1) {
        return;
      }
      this.setData({
        opcity: opcity
      });
    }
  })
}

export function cc (){
  return Component({
    properties:{
      padding:{
        type:String,
        value:"0 18rpx 0 10rpx"
      }
    },
    data:{
      cc:""
    },
    methods: {
      清空(){
        this.triggerEvent("cc")
      }
    }
  })
}

export function dy (){
  return Component({
    properties: {
      src:{
        type:String,
        value:""
      },
      src2:{
        type:String,
        value:""
      },
      tb:{
        type:Number,
        value:""
      }
    },
    methods:{
      click(){
        this.triggerEvent('click')
      }
    }
  })
}

export function height(){
  return Component({
    properties: {
      height: Number,
      h:Number
      }
  })
}

export function modal (){
  return Component({
    externalClasses: ['tui-modal-class'],
    properties: {
      //是否显示
      show:{
        type:Boolean,
        value:false
      },
      width: {
        type: String,
        value: "84%"
      },
      t_top: {
        type: String,
        value: "50%"
      },
      padding: {
        type: String,
        value: "40rpx 64rpx"
      },
      radius: {
        type: String,
        value: "24rpx"
      },
      //标题
      title: {
        type: String,
        value: ""
      },
      //内容
      content: {
        type: String,
        value: ""
      },
      //内容字体颜色
      color: {
        type: String,
        value: "#999"
      },
      //内容字体大小
      size: {
        type: Number,
        value: 28
      },
      //形状 circle, square
      shape: {
        type: String,
        value: 'square'
      },
      button: {
        type: Array,
        value: [{
          text: "取消",
          type: "red",
          plain: true //是否空心
        }, {
          text: "确定",
          type: "red",
          plain: false
        }]
      },
      //点击遮罩 是否可关闭
      maskClosable: {
        type: Boolean,
        value: true
      },
      //自定义弹窗内容
      custom:{
        type:Boolean,
        value:false
      },
      //淡入效果，自定义弹框插入input输入框时传true
      fadein: {
        type: Boolean,
        value: false
      }
  
    },
    data: {
  
    },
    methods: {
      handleClick(e) {
        if (!this.data.show) return;
        const dataset = e.currentTarget.dataset;
        this.triggerEvent('click', {
          index: Number(dataset.index)
        });
      },
      handleClickCancel() {
        if(!this.data.maskClosable) return;
        this.triggerEvent('cancel');
      },
      forbid(){}
    }
  })
}

export function notice (){
  const VALID_MODE = ['closeable'];
const FONT_COLOR = '#f60';
const BG_COLOR = '#fff7cc';

 return Component({
    externalClasses: ['i-class'],
    properties: {
        fontsize:{
            type:Number,
            value:26
        },
        closable: {
            type: Boolean,
            value: false
        },
        content: {
            type: String,
            value: ''
        },
        icon: {
            type: String,
            value: 'systemprompt'
        },
        loop: {
            type: Boolean,
            value: true
        },
        // 背景颜色
        backgroundcolor: {
            type: String,
            value: ''
        },
        // 字体及图标颜色
        color: {
            type: String,
            value: '#f76a24'
        },
        // 滚动速度
        speed: {
            type: Number,
            value: 1500
        },
        margin:{
            type: String,
            value: '0 20rpx'
        }
    },

    data: {
        show: true,
        wrapWidth: 0,
        width: 0,
        duration: 0,
        animation: null,
        timer: null,
    },
    detached() {
        this.销毁定时器();
    },
    attached() {
        if (this.data.loop) {
            this.初始化动画();
        }
    },

    methods: {
        初始化动画() {
            wx.createSelectorQuery().in(this).select('.i-noticebar-content-wrap').boundingClientRect((wrapRect) => {
                wx.createSelectorQuery().in(this).select('.i-noticebar-content').boundingClientRect((rect) => {
                    const duration = rect.width / 40 * this.data.speed;
                    const animation = wx.createAnimation({
                        duration: duration,
                        timingFunction: "linear",
                    });
                    this.setData({
                        wrapWidth: wrapRect.width,
                        width: rect.width,
                        duration: duration,
                        animation: animation
                    }, () => {
                        this.开始动画();
                    });
                }).exec();

            }).exec();
        },
        开始动画() {
            //reset
            if (this.data.animation.option.transition.duration !== 0) {
                this.data.animation.option.transition.duration = 0;
                const resetAnimation = this.data.animation.translateX(this.data.wrapWidth).step();
                this.setData({
                    animationData: resetAnimation.export()
                });
            }
            this.data.animation.option.transition.duration = this.data.duration;
            const animationData = this.data.animation.translateX(-this.data.width).step();
            setTimeout(() => {
                this.setData({
                    animationData: animationData.export()
                });
            }, 100);
            const timer = setTimeout(() => {
                this.开始动画();
            }, this.data.duration);
            this.setData({
                timer,
            });
        },
        销毁定时器() {
            if (this.data.timer) {
                clearTimeout(this.data.timer);
            }
        },
        关闭(e) {
            this.销毁定时器();
            this.setData({
                show: false,
                timer: null
            });
            this.triggerEvent('close', e);
        }
    }
})
}

export function qsy (){
  return Component({
    properties: {
      width:{
        type:Number,
        value:''
      },
      radius:{
        type:Number,
        value:''
      },
      color:{
        type:String,
        value:'blue'
      },
      qsy:{
        type:String,
        value:'去水印'
      },
    },
    methods: {
      去水印(){
        this.triggerEvent("cc")
      }
    }
  })
}

export function tip(){
  let timer;
  return Component({
    externalClasses: ['tui-tips-class'],
    properties: {
      //top bottom center
      position: {
        type: String,
        value: "top"
      }
    },
    data: {
      show: false,
      msg: "再看就把你关掉~",
      //translucent,primary,green,warning,danger
      type: "translucent"
    },
    lifetimes: {
      detached: function() {
        clearTimeout(timer);
        timer = null;
      }
    },
    methods: {
      showTips: function(options) {
        const {type = 'translucent', duration = 2000} = options;
        clearTimeout(timer);
        this.setData({
          show: true,
          type: type,
          msg: options.msg
        }, () => {
          timer = setTimeout(() => {
            this.setData({
              show: false
            }, () => {
              timer = null;
            })
          }, duration)
        })
      }
    }
  })
}

export function ys(){
  var _animation; 
  // 动画实体
  var _animationIndex = 0; 
  // 动画执行次数index（当前执行了多少次）
  var _animationIntervalId = -1; 
  // 动画定时任务id，通过setInterval来达到无限旋转，记录id，用于结束定时任务
  const _ANIMATION_TIME = 2500; 
  // 动画播放一次的时长ms
 return Component({
    properties:{
      mtg:{
        type:Number,
        value:0
      },
      mytx:{
        type:String,
        value:"https://thirdwx.qlogo.cn/mmopen/vi_32/Kfsq4rlKCRz19mtK8oGo91icUNibicsyUnrMrGX2QxRo2kLyIYuOVAN967kghic3cM5Q6VS5QDdYHDicj2Sek9t9rMQ/132"
      }
    },
    methods: {
      /**
       * 实现image旋转动画，每次旋转 120*n度
       */
      初始化(n) {
        _animation.rotate(120 * (n)).step()
        this.setData({
          animation: _animation.export()
        })
      },
      /**
       * 开始旋转
       */
      开始旋转() {
        var that = this;
        that.初始化(++_animationIndex); // 进行一次旋转
        _animationIntervalId = setInterval(function () {
          that.初始化(++_animationIndex);
        }, _ANIMATION_TIME); // 每间隔_ANIMATION_TIME进行一次旋转
      }
    },
    ready() {
      _animationIndex = 0;
      _animationIntervalId = -1;
      this.data.animation = '';
    },
    attached() {
      _animation = wx.createAnimation({
        duration: _ANIMATION_TIME,
        timingFunction: 'linear',
        // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
        delay: 0,
        transformOrigin: '50% 50% 0'
      })
      this.开始旋转();
    }
  })
}